<?php
namespace app\common\upload;


use Closure;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use think\facade\Db;
use think\facade\Env;

class QiniuUpload extends LocalUpload
{

    private $accessKey;
    private $secretKey;
    private $bucket;
    private $domain;
    public function __construct()
    {
        $this->accessKey=Env::get('qiniu.qiniu_access_key');
        $this->secretKey=Env::get('qiniu.qiniu_secret_key');
        $this->bucket=Env::get('qiniu.qiniu_bucket');
        $this->domain=Env::get('qiniu.qiniu_domain');
    }
    //将上传的图片插入记录
    public static function addRecord($ret,$url,$oriName,$type){
        Db::name('pic')->insert([
            'url'=>$url,'title'=>$oriName,
            'type'=>$type,
            'last_time'=>date('Y-m-d H:i:s'),
            'fsize'=>$ret['fsize'],
            'mime_type'=>$ret['mimeType'],
            'hash'=>$ret['hash'],
        ]);
    }
    //上传本地图片值七牛云
    public function upload($type='远程抓取'){
        $res=parent::upload($type);
        if($res['code']!==0){
            return $res;
        }
        $filePath=$res['localPath'];
        $oriName=$res['originalName'];
        $fileName=$res['fileName'];
        $localPath=$res['localPath'];
        $key=str_replace('\\','/',$res['fileName']);//替换\斜杠
        // 构建鉴权对象
        $auth = new Auth($this->accessKey, $this->secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        $res = $uploadMgr->putFile($token, $key, $filePath);
        if($res[1]==null){ //上传成功
            $url=$this->domain.$key;
            self::addRecord($res[1],$url,$oriName,$type);
            return array("code"=>0, 'url' =>$url, 'originalName' => $oriName,"fileName"=>$fileName,"localPath"=>$localPath);
        }else{//上传失败
            return array("code"=>501, "msg"=>"上传失败");
        }
    }

    //抓取远程图片保存至七牛云
    public function uploadLink($url,$type='远程抓取'){
        $oriName=null;
        $auth = new Auth($this->accessKey, $this->secretKey);
        $bucketManager = new BucketManager($auth);
        $ori=self::getNameFromUrl($oriName);
        $oriName=$oriName?$oriName:$ori['oriName'];
        $houzui=$ori['houzui'];
        $key='fetch/'.time().mt_rand(1000,9999).'.'.$houzui;
        // 不指定key时，以文件内容的hash作为文件名
        list($ret, $err) = $bucketManager->fetch($url, $this->bucket, $key);
        //$ret  array(4) { ["fsize"]=> int(252814) ["hash"]=> string(28) "FqE4mDbyked_xczt998IX51XKJku" ["key"]=> string(24) "fetch/15781492009595.jpg" ["mimeType"]=> string(10) "image/jpeg" }
        if ($err == null) {
            $url=$this->domain.$key;
            self::addRecord($ret,$url,$oriName,$type);
            return array("code"=>0,'state' => 'success','url' =>$url, 'title' => $url);
        } else {
            return array("code"=>404,'state' => 'EROOR', 'title' => '上传图片为空！');;
        }
    }
    public static function getNameFromUrl($url){
        $preg='/.+\/(.+)$/is';
        preg_match($preg,$url,$preg_res);
        $oriName=isset($preg_res[1])?$preg_res[1]:$url;
        $oriNameArray= explode('.',$oriName);
        $len=count($oriNameArray);
        if($len>1){
            $huozui=$oriNameArray[$len-1];
        }else{
            $huozui='jpg';
        }
        return array('oriName'=>$oriName,'houzui'=>$huozui);
    }

    /**
     * https://developer.qiniu.com/kodo/api/1284/list#list-description
     *  array (size=8)
        'key' => string 'fetch/15781492009595.jpg' (length=24)
        'hash' => string 'FqE4mDbyked_xczt998IX51XKJku' (length=28)
        'fsize' => int 252814
        'mimeType' => string 'image/jpeg' (length=10)
        'putTime' => int 15781492002804882
        'type' => int 0
        'status' => int 0
        'md5' => string '23dd0f9e61f69b498f0de4ec96bf060e' (length=32)
     */
    public function getFiles($prefix,$limit=1000, $delimiter='',Closure $f=null){
        $auth = new Auth($this->accessKey, $this->secretKey);
        $bucketManager = new BucketManager($auth);
        $has_next=true;
        $marker='';
        $limit=$limit>1000?1000:$limit;
        $items=array();
        while ($has_next&&count($items)<$limit){
            list($ret, $err) = $bucketManager->listFiles($this->bucket, $prefix, $marker, $limit, $delimiter);
            if ($err !== null) {
                //出错
                $has_next=false;
            } else {
                if (array_key_exists('marker', $ret)) {
                    $marker=$ret["marker"];
                }else{
                    $has_next=false;
                }
                if($f){
                    $f($ret['items']);
                }
                $items=array_merge($items,$ret['items']);
            }
        }
        return $items;
    }



}